<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>移除无效的括号</title>
</head>
<body>
  <script>
    function fn(s) {
      let res = [...s];
      //栈匹配括号，剩下括号删除
      let stack = [];
      for (let i = 0; i < s.length; i++) {
        if (s[i] === '(') {
          stack.push(i);
        } else if (s[i] === ')') {
          if (stack.length > 0) {
            stack.pop();
          } else {
            delete (res[i]); //栈为空，没有左括号，把当前右括号删除
          }
        }
      }
      while (stack.length) { //删除栈顶元素直到栈空
        delete (res[stack.pop()]);
      }
      return res.join('');
    }
    console.log(fn('lee(t(c)o)de)'))
  </script>
</body>
</html>